package com.helasasa.maxfunds.lineofcredit.cashloan.cameroon.screen.myprofile

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.helasasa.maxfunds.lineofcredit.cashloan.R
import com.helasasa.maxfunds.lineofcredit.cashloan.cameroon.http.hitPointCameroon
import com.helasasa.maxfunds.lineofcredit.cashloan.cameroon.screen.subview.HotlineCameroonDialog
import com.helasasa.maxfunds.lineofcredit.cashloan.databinding.ActivityCameroonMyProfileBinding
import org.json.JSONObject

class MyProfileCameroonActivity : AppCompatActivity() {

    private lateinit var myProfileViewModel: MyProfileCameroonViewModel
    private lateinit var binding: ActivityCameroonMyProfileBinding
    private lateinit var adapter: MyProfileCameroonPageAdapter

    @SuppressLint("NotifyDataSetChanged")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // 数据模型
        myProfileViewModel = ViewModelProvider(this)[MyProfileCameroonViewModel::class.java]

        // 关联布局
        binding = ActivityCameroonMyProfileBinding.inflate(layoutInflater)
        setContentView(binding.root)

        // 用到的控件
        val hotline = binding.navbarRight
        val back = binding.navbarLeft
        val list = binding.list
        val bottomBg = binding.bottomBg
        val apply = binding.apply
        val loading = binding.loading

        // 初始化adapter
        adapter = MyProfileCameroonPageAdapter(emptyList(), object : IMyProfileCameroonPageListener {
            override fun onClick(step: String, stepTitle: String) {
                // 查看详情
                val hashMap = HashMap<String, String>().apply {
                    put("step", step)
                    put("stepTitle", stepTitle)
                }
                startNextActivity(MyProfileCameroonDetailActivity::class.java, hashMap)
            }
        })
        list.layoutManager = LinearLayoutManager(this)
        list.adapter = adapter

        // 页面loading状态接口监听
        myProfileViewModel.loadingResult.observe(this@MyProfileCameroonActivity, Observer {
            val loadingResult = it ?: return@Observer

            if (loadingResult) {
                loading.visibility = View.VISIBLE
            } else {
                loading.visibility = View.GONE
            }
        })

        // 页面UI状态接口监听
        myProfileViewModel.pageDetailResult.observe(this@MyProfileCameroonActivity, Observer {
            val pageDetailResult = it ?: return@Observer

            loading.visibility = View.GONE
            if (pageDetailResult.error != null) {
                showMessage(pageDetailResult.error)
            }
            if (pageDetailResult.items != null) {
                // 渲染
                adapter.dataList = pageDetailResult.items
                adapter.notifyDataSetChanged()

                val hasNotDone = pageDetailResult.items.any { item ->
                    item.optString("done") == "NO"
                }
                bottomBg.visibility = if (hasNotDone) View.VISIBLE else View.GONE
            }
            if (pageDetailResult.hadApply == true) {
                // 如果已申请过，不能修改
                bottomBg.visibility = View.GONE
            }
        })

        // 流程接口监听
        myProfileViewModel.mainProcessResult.observe(this@MyProfileCameroonActivity, Observer {
            val mainProcessResult = it ?: return@Observer

            loading.visibility = View.GONE
            if (mainProcessResult.error != null) {
                showMessage(mainProcessResult.error)
            }

            if (mainProcessResult.success != null) {
                myProfileViewModel.nextRouter(mainProcessResult.success)
            }
        })

        // 页面需要跳转监听
        myProfileViewModel.nextRouterResult.observe(this@MyProfileCameroonActivity, Observer {
            val nextRouterResult = it ?: return@Observer

            loading.visibility = View.GONE
            startNextActivity(nextRouterResult.nextPage)
        })

        // 点击客服
        hotline.setOnClickListener {
            // 客服弹框
            HotlineCameroonDialog().showNow(supportFragmentManager, "hotline")
            hitPointCameroon("SHOW_HOTLINE")
        }

        // 点击返回
        back.setOnClickListener {
            finish()
        }

        // 点击apply
        apply.setOnClickListener {
            myProfileViewModel.mainProcess()

            hitPointCameroon("MY_PROFILE_APPLY_COMMIT")
        }

        // 拉回显
        loading.visibility = View.VISIBLE
        myProfileViewModel.pageDetail()
    }

    override fun onResume() {
        super.onResume()
        hitPointCameroon(type = this::class.java.simpleName, isPageStart = true)
    }

    override fun onPause() {
        super.onPause()
        hitPointCameroon(type = this::class.java.simpleName, isPageEnd = true)
    }
}

interface IMyProfileCameroonPageListener {
    fun onClick(step: String, stepTitle: String)
}

class MyProfileCameroonPageAdapter(
    var dataList: List<JSONObject>,
    var onClick: IMyProfileCameroonPageListener? = null
) :
    RecyclerView.Adapter<MyProfileCameroonPageAdapter.ViewHolder>() {

    override fun onCreateViewHolder(
        parent: ViewGroup,
        viewType: Int,
    ): ViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.view_cameroon_my_profile_activity_adapter, parent, false)
        return ViewHolder(view)
    }

    inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val title: TextView = view.findViewById(R.id.title)
        val icon: ImageView = view.findViewById(R.id.icon)
        val ext: ImageView = view.findViewById(R.id.ext)
        val container: LinearLayout = view.findViewById(R.id.container)

        fun bindData(item: JSONObject) {
            val step = item.optString("step")
            val stepTitle = item.optString("stepTitle")
            title.text = stepTitle

            val done = item.optString("done")
            if (done == "YES") {
                title.setTextColor(Color.parseColor("#222222"))
                icon.setImageResource(R.drawable.pic_proof_done)
                ext.visibility = View.VISIBLE
            } else {
                title.setTextColor(Color.parseColor("#999999"))
                icon.setImageResource(R.drawable.pic_proof_undone)
                ext.visibility = View.GONE
            }

            container.setOnClickListener {
                if (done == "YES") {
                    onClick?.onClick(step, stepTitle)
                }
            }
        }
    }

    @SuppressLint("SetTextI18n")
    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val data: JSONObject = dataList[position]
        holder.bindData(data)
    }

    override fun getItemCount(): Int {
        return dataList.size
    }
}

fun Context.showMessage(message: String) {
    Toast.makeText(applicationContext, message, Toast.LENGTH_SHORT).show()
}

fun Context.startNextActivity(
    activity: Class<out AppCompatActivity>? = null,
    params: HashMap<String, String> = HashMap()
) {
    val nextActivity = activity ?: return
    try {
        val intent = Intent(this, nextActivity)
//        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_NEW_TASK)
        params.keys.forEach { gKey ->
            intent.putExtra(gKey, params[gKey])
        }
        startActivity(intent)
    } catch (e: Exception) {
        e.printStackTrace()
    }
}